package com.weiyin.examination.course;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.bumptech.glide.Glide;
import com.weiyin.examination.R;
import com.weiyin.examination.application.Constant;
import com.weiyin.examination.dialog.CourseDialog;
import com.weiyin.examination.http.RetrofitClient;
import com.weiyin.examination.listener.CourseInterface;
import com.weiyin.examination.listener.DialogShowListener;
import com.weiyin.examination.module.AnswerModule;
import com.weiyin.examination.module.TestModule;
import com.weiyin.examination.util.AudioRecoderUtils;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.SPUtil;

import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * Created by darkshadow on 2018/7/3.
 */

public class CourseAudio1 extends Course {
    private View rootView;
    private Activity activity;
    private ClickAble clickAble;


    private TextView titleLayoutNextTextView, titleLayoutLastTextView,
            titleLayoutSubjectContentTextView, titleLayoutSubjectScoreTextView,
            titleLayoutNumberTextView, titleTicketNumber, title_content, ok, playRecord;
    private RelativeLayout titleLayoutNumberRl, re_record_rl;
    private ImageView courseView;
    private TestModule testModule;
    private List<TestModule> testModuleList;
    private List<AnswerModule> answerModuleList;
    private MediaPlayer mediaPlayer;

    private int courseIndex, mediaIndex;

    private Handler mHandler = new Handler();

    private LayoutHelper layoutHelper;

    private ImageView image;

    private AnimationDrawable animationDrawable;

    private CourseDialog courseDialog;
    private AudioRecoderUtils mAudioRecoderUtils;

    private String file;


    private int viewId;

    private boolean isOnclik = true;

    @Override
    public void onCreate(Activity activity, ViewFlipper contain, List<TestModule> courseEntities, int index) {
        if (rootView == null) {
            rootView = LayoutInflater.from(activity).inflate(R.layout.course_audio1, null);
            layoutHelper = new LayoutHelper(activity);
            layoutHelper.scaleView(rootView);
            contain.addView(rootView);
            this.testModuleList = courseEntities;
            this.activity = activity;
            this.courseIndex = index;
            if (index > -1) {
                this.testModule = testModuleList.get(index);
            }
            clickAble = new ClickAble();
            mediaPlayer = new MediaPlayer();
            if (testModule != null) {
                if (testModule.getRightAnswerList() != null) {
                    this.answerModuleList = testModule.getRightAnswerList();
                }
            }
            initView();
            mediaIndex = 0;
        }
    }

    @Override
    public void initView() {
        ok = rootView.findViewById(R.id.ok);
        re_record_rl = rootView.findViewById(R.id.re_record_rl);
        titleLayoutNextTextView = (TextView) rootView.findViewById(R.id.titleLayoutNextTextView);
        titleLayoutLastTextView = (TextView) rootView.findViewById(R.id.titleLayoutLastTextView);
        titleLayoutSubjectContentTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectContentTextView);
        titleLayoutSubjectScoreTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectScoreTextView);
        titleLayoutNumberTextView = (TextView) rootView.findViewById(R.id.titleLayoutNumberTextView);
        titleTicketNumber = (TextView) rootView.findViewById(R.id.titleTicketNumber);
        title_content = rootView.findViewById(R.id.title_content);
        titleLayoutNumberRl = (RelativeLayout) rootView.findViewById(R.id.titleLayoutNumberRl);
        courseView = rootView.findViewById(R.id.courseView);
        titleLayoutNextTextView.setOnClickListener(clickAble);
        titleLayoutLastTextView.setOnClickListener(clickAble);
        titleLayoutNumberRl.setOnClickListener(clickAble);
        ok.setOnClickListener(clickAble);
        re_record_rl.setOnClickListener(clickAble);
        image = (ImageView) rootView.findViewById(R.id.image);
        playRecord = rootView.findViewById(R.id.playRecord);

        mAudioRecoderUtils = new AudioRecoderUtils();
        playRecord.setOnClickListener(clickAble);
        //录音回调
        mAudioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {

            //录音中....db为声音分贝，time为录音时长
            @Override
            public void onUpdate(double db, long time) {
            }

            //录音结束，filePath为保存路径
            @Override
            public void onStop(String filePath) {
                file = filePath;
                SPUtil.setSharedPreferencesData(activity, "courseAudio1", filePath);
            }
        });
    }

    private void initViewData() {
        if (testModule != null) {

            titleTicketNumber.setText("准考证号：" + "" + testModule.getTickNumber());
            titleLayoutLastTextView.setVisibility(courseIndex == 0 ? View.GONE : View.VISIBLE);
            titleLayoutNextTextView.setVisibility(courseIndex == testModuleList.size() - 1 ? View.GONE : View.VISIBLE);

            titleLayoutSubjectScoreTextView.setText("（" + testModule.getScore() + "分）");
            titleLayoutNumberTextView.setText("第" + (courseIndex + 1) + "题/第" + (testModuleList.size()) + "题");
            titleLayoutSubjectContentTextView.setText((courseIndex + 1) + "丶 视唱题");
            title_content.setText(testModule.getSubjectTitle());
            Glide.with(activity).
                    load(RetrofitClient.BASE_URL + testModule.getSubjectUrl()).
                    into(courseView);
        }

        if (mediaIndex == 0) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mediaPlayerPlay(activity.getExternalFilesDir(null) +
                            testModule.getMp3UrlList().get(mediaIndex).getMp3Url()
                                    .replace("/", ""), false);
                }
            }, 500);
        }
    }


    class ClickAble implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.playRecord:
                    if (StringUtils.isEmpty(file)) {
                        return;
                    }
                    mediaPlayerStop();
                    mediaPlayerPlay(file, false);
                    break;
                case R.id.ok:
                    isOnclik = false;
                    mediaPlayerStop();
                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    break;
                case R.id.re_record_rl:
                    mediaIndex = 1;
                    mediaPlayerStop();
                    mediaPlayerPlay(activity.getExternalFilesDir(null) + testModule.getMp3UrlList().get(mediaIndex).getMp3Url().replace("/", ""), true);
                    break;
                case R.id.titleLayoutNextTextView:
                    if (isOnclik) {
                        viewId = v.getId();
                        showDialog();
                    } else {
                        next();
                    }
                    break;
                case R.id.titleLayoutLastTextView:
                    if (isOnclik) {
                        viewId = v.getId();
                        showDialog();
                    } else {
                        last();
                    }
                    break;
                case R.id.titleLayoutNumberRl:
                    if (isOnclik) {
                        viewId = v.getId();
                        showDialog();
                    } else {
                        skip();
                    }

                    break;
                default:

                    break;
            }
        }
    }

    private void next() {
        mediaPlayerStop();
        dialogShowListener.dialogShow(1, courseIndex, resultMap());
        courseInterface.courseInterfaceResult(Constant.NEXT_KNOWLEDGE, courseIndex + 1);

    }

    private void last() {
        mediaPlayerStop();
        dialogShowListener.dialogShow(1, courseIndex, resultMap());
        courseInterface.courseInterfaceResult(Constant.LAST_KNOWLEDGE, courseIndex - 1);

    }

    private void skip() {
        dialogShowListener.dialogShow(1, courseIndex, resultMap());
        dialogShowListener.dialogShow(0, courseIndex, resultMap());
        mediaPlayerStop();
    }

    private void mediaPlayerPlay(String mp3Path, final boolean record) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(mp3Path);
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    mediaIndex++;
                    if (record) {
                        mAudioRecoderUtils.startRecord(SPUtil.getSharedPreferencesData(activity, "number", "") + SPUtil.getSharedPreferencesData(activity, "level", "") + testModule.getTickNumber() + "_" + (courseIndex + 1));
                        image.setImageResource(R.drawable.record_selector);
                        animationDrawable = new AnimationDrawable();
                        animationDrawable = (AnimationDrawable) image.getDrawable();
                        animationDrawable.start();
                    }
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    try {
                        mp.reset();
                        if (mediaIndex == 1) {
                            mediaPlayerPlay(activity.getExternalFilesDir(null) + testModule.getMp3UrlList().get(mediaIndex).getMp3Url().replace("/", ""), true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void mediaPlayerStop() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
        }
        if (animationDrawable != null) {
            animationDrawable.stop();
            image.setImageResource(R.drawable.item1);
        }
        if (mAudioRecoderUtils != null) {
            mAudioRecoderUtils.stopRecord();
        }
    }

    private boolean resultMap() {

//        Constant.getScreen(activity, SPUtil.getSharedPreferencesData(activity, "number") + "_" + (courseIndex + 1),SPUtil.getSharedPreferencesData(activity, "number")+"_"+ (courseIndex + 1));
        if (StringUtils.isEmpty(file)) {
            return false;
        } else {
            return true;
        }
    }

    private void showDialog() {
        if (courseDialog == null) {
            String txt = activity.getResources().getString(R.string.coursePrompt);
            courseDialog = new CourseDialog(activity, R.style.BlueToothDialogStyle, txt);
        }
        if (!courseDialog.isShowing()) {
            courseDialog.show();
        }
        courseDialog.setCourseDialogInterlisteren(new CourseDialog.CourseDialogListener() {
            @Override
            public void courseDialogResult(int type) {
                if (type == 1) {
                    mediaIndex = testModule.getMp3UrlList().size();
                    isOnclik = false;
                    if (viewId == R.id.titleLayoutNextTextView) {
                        next();
                    } else if (viewId == R.id.titleLayoutLastTextView) {
                        last();
                    } else if (viewId == R.id.titleLayoutNumberRl) {
                        skip();
                    }
                }
            }
        });
    }

    @Override
    public void setCourseInterface(CourseInterface courseInterface) {
        this.courseInterface = courseInterface;
    }

    @Override
    public void setCourseDialogListener(DialogShowListener dialogListener) {
        this.dialogShowListener = dialogListener;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void show(List<TestModule> courseEntities, int index, String type) {
        initViewData();
    }

    @Override
    public void stop() {
        if (mAudioRecoderUtils != null) {
            mAudioRecoderUtils.stopRecord();
        }
        mHandler.removeCallbacksAndMessages(null);
        mediaPlayerStop();
    }

    @Override
    public void destroy() {
        if (mAudioRecoderUtils != null) {
            mAudioRecoderUtils.stopRecord();
        }
        mHandler.removeCallbacksAndMessages(null);
        mediaPlayerStop();
    }
}
